function $(dom) {
  return document.querySelector(dom)
}
function $2(dom) {
  return document.querySelectorAll(dom)
}
// 本地存储
function save(arr, value) {
  localStorage.setItem(value, JSON.stringify(arr))
}
let arr = localStorage.getItem('value') === null ? [] : JSON.parse(localStorage.getItem('value'))
// 方向盘的定时器
let timerController = null
// 键盘移动的定时器
let timerkey = null
// 计时的定时器
let timedate = null
// 主机发射子弹的定时器
let timelatnch = null
// 子弹继续射击定时器
let timeContinue = null
// 敌方子弹继续射击定时器
let timeContinue2 = null
// 敌机动画定时器
let timeEnemyanimation = null
// 友机动画定时器
let timeFriendlyAnimation = null
// 生成飞机的定时器
let timeCreateAir = null
// 敌机发射子弹的定时器
let timeEnemyBullet = null
// 飞机的移动速度
let speed = 2
// 主机子弹的发射速度
let laynchSpeed = 10
// 敌机子弹的发射速度
let enemySpeed = 5
// 主机子弹发射开关
let laynchFlg = true
// 分数
let fraction = 0
// 时间
let timeIndex = 0;
// 音乐开关
let music = true
// 暂停开关
let pause_game = false
// 存数据
let obj = {}
// 游戏结束
let gameEnd = true
// 开始
$(".start").onclick = function () {
  // 关闭说明
  $(".gameStart").style.display = "none"
  // 背景移动
  $(".background").style.animation = "run 40s linear infinite"
  // 飞机显示
  $('.aircraft_cont').style.animation = "moveRight 0.8s ease-in-out"
  $('.aircraft_cont').style.opacity = "1"
  // 播放背景音乐
  $("#background").play()
  // 方向盘显示
  $(".controller_box").style.animation = "show1 1.6s ease-in-out forwards"
  // 游戏信息显示
  $('.gameInfo').style.opacity = 1
  // 方向盘移动位置
  controller()
  // 键盘移动位置
  keyboard()
  // 计时
  startTime()
  // 主机子弹发射
  weLaynch()
  // 飞行物的创建
  createAircraft()
  // 飞机的动画
  enemyAnmiation()
  friendlyAnmiation()
  // 字体大小
  fontChange()
}
// 音乐按钮
$(".pause_music").onclick = function () {
  if (gameEnd) {
    music = !music
    pause_music()
  }
}
// 暂停按钮
$(".pause_game").onclick = function () {
  if (gameEnd) pause_games()
}
document.addEventListener('keydown', function (e) {
  if (gameEnd) {
    if (e.key == 'p') pause_games()
  }
})
// 重新开始
$(".restart").onclick = function () {
  location.reload()
}
// 改变字体大小
function fontChange() {
  let i = 0
  $(".maxSize").onclick = function () {
    if (gameEnd) {
      i += 1
      let fontSize = Number(getComputedStyle($("html"), null)['fontSize'].substring(0, getComputedStyle($("html"), null)['fontSize'].length - 2))
      $('html').style.fontSize = fontSize + i + 'px'
      i = 0
    }
  }
  $(".minSize").onclick = function () {
    if (gameEnd) {
      i -= 1
      let fontSize = Number(getComputedStyle($("html"), null)['fontSize'].substring(0, getComputedStyle($("html"), null)['fontSize'].length - 2))
      $('html').style.fontSize = fontSize + i + 'px'
      i = 0
    }
  }
}
// 方向盘移动位置
function controller() {
  document.onmouseover = function (e) {
    if (gameEnd) {
      if (!pause_game) {
        let target = e.target
        if (target.className.indexOf('item_img') > -1) {
          clearInterval(timerController)
          let index = target.getAttribute('index')
          let aircraft = $(".aircraft_cont")
          let left = Number(getComputedStyle(aircraft, null)['left'].substring(0, getComputedStyle(aircraft, null)['left'].length - 2))
          let top = Number(getComputedStyle(aircraft, null)['top'].substring(0, getComputedStyle(aircraft, null)['top'].length - 2))
          timerController = setInterval(() => {
            if (index == "top") {
              if (top <= 0) {
                aircraft.style.top = top + 'px'
              } else {
                top -= speed
                aircraft.style.top = top + 'px'
              }
            } else if (index == "left") {
              if (left <= 10) {
                aircraft.style.left = left + 'px'
              } else {
                left -= speed
                aircraft.style.left = left + 'px'
              }
            } else if (index == "right") {
              if (left >= document.body.clientWidth - 50) {
                aircraft.style.left = left + 'px'
              } else {
                left += speed
                aircraft.style.left = left + 'px'
              }
            } else if (index == "bottom") {
              if (top >= document.body.clientHeight - 50) {
                aircraft.style.top = top + 'px'
              } else {
                top += speed
                aircraft.style.top = top + 'px'
              }
            }
          }, 1)
        } else if (target.className.indexOf('background') > -1) {
          clearInterval(timerController)
        }
      }
    }
  }
}
// 键盘移动位置
function keyboard() {
  let flg = { up: false, down: false, left: false, right: false }
  let aircraft = $(".aircraft_cont")
  document.addEventListener("keydown", function (e) {
    if (e.key == 'ArrowUp') {
      flg.up = true;
    } else if (e.key == "ArrowLeft") {
      flg.left = true;
    } else if (e.key == "ArrowRight") {
      flg.right = true;
    } else if (e.key == "ArrowDown") {
      flg.down = true;
    }
  })
  document.onkeyup = function (e) {
    if (e.key == 'ArrowUp') {
      flg.up = false;
    } else if (e.key == "ArrowLeft") {
      flg.left = false;
    } else if (e.key == "ArrowRight") {
      flg.right = false;
    } else if (e.key == "ArrowDown") {
      flg.down = false;
    }
  }
  timerkey = setInterval(() => {
    let left = Number(getComputedStyle(aircraft, null)['left'].substring(0, getComputedStyle(aircraft, null)['left'].length - 2))
    let top = Number(getComputedStyle(aircraft, null)['top'].substring(0, getComputedStyle(aircraft, null)['top'].length - 2))
    if (flg.up) {
      if (top <= 0) {
        aircraft.style.top = top + 'px'
      } else {
        top -= speed
        aircraft.style.top = top + 'px'
      }
    }
    if (flg.left) {
      if (left <= 10) {
        aircraft.style.left = left + 'px'
      } else {
        left -= speed
        aircraft.style.left = left + 'px'
      }
    }
    if (flg.right) {
      if (left >= document.body.clientWidth - 50) {
        aircraft.style.left = left + 'px'
      } else {
        left += speed
        aircraft.style.left = left + 'px'
      }
    }
    if (flg.down) {
      if (top >= document.body.clientHeight - 50) {
        aircraft.style.top = top + 'px'
      } else {
        top += speed
        aircraft.style.top = top + 'px'
      }
    }
  }, 1)
}
// 计时
function startTime() {
  let i = 0
  timedate = setInterval(() => {
    i++
    if (i > 100) {
      i = 0
      timeIndex++
      // 进度条
      let width = Number(getComputedStyle($(".progress"), null)['width'].substring(0, getComputedStyle($(".progress"), null)['width'].length - 2))
      width -= 3.33
      $(".fuelCounter span").innerHTML = Math.floor(width / 3.33) < 1 ? 0 : Math.floor(width / 3.33)
      $(".progress").style.width = width + 'px'
      if (width <= 0) {
        pause_games()
        $(".infoTable").style.transform = "translate(-50%,-50%) scale(1.5)"
        endGame()
        gameEnd = false
      }
      // 秒计时
      $(".time").innerHTML = `${timeIndex}秒`
    }
  }, 10)
}
// 主机子弹发射
function weLaynch() {
  document.addEventListener('keydown', function (e) {
    if (e.code == "Space" && !pause_game) {
      if (laynchFlg) {
        laynchFlg = false
        let left = $(".aircraft_cont").offsetLeft
        let top = $(".aircraft_cont").offsetTop
        let node = document.createElement("div")
        node.className = "laynch_item"
        $(".laynch").appendChild(node)
        music ? $("#shoot").play() : $("#shoot").pause()
        timelatnch = setInterval(() => {
          left += laynchSpeed
          node.style.left = left + 'px'
          node.style.top = top + 20 + 'px'
          if (left >= document.body.clientWidth) node.remove()
        }, 1)
      }
    }
  })
  document.addEventListener('keyup', function (e) {
    laynchFlg = true
  })
}
// 飞行物的创建
function createAircraft() {
  let i = 0, y = 0, x = 0, s = 0, d = 0, r = 0;
  timeCreateAir = setInterval(() => {
    let height = document.body.clientHeight - 70
    let randomHeight = Math.round(Math.random() * height)
    // 敌机
    i++
    if (i > 300) {
      i = 0
      let enemyNode = document.createElement("div")
      enemyNode.className = 'enemy_item'
      enemyNode.style.top = randomHeight + 'px'
      enemyNode.innerHTML = `<img src="" alt="">`
      $(".enemy").appendChild(enemyNode)
    }
    // 敌机销毁
    $2(".enemy_item").forEach(item => item.offsetLeft <= -50 ? item.remove() : '')

    // 友机
    y++
    if (y > 500) {
      y = 0
      let friendlyNode = document.createElement("div")
      friendlyNode.className = 'friendly_item'
      friendlyNode.style.top = randomHeight + 'px'
      friendlyNode.innerHTML = `<img src="" alt="">`
      $(".friendly").appendChild(friendlyNode)
    }
    // 友机销毁
    $2(".friendly_item").forEach(item => item.offsetLeft <= -50 ? item.remove() : '')

    // 敌机发射子弹
    d++
    if (d > 80) {
      d = 0
      if ($2('.enemy_item').length !== 0) {
        $2('.enemy_item').forEach(item => {
          let left = item.offsetLeft
          let top = item.offsetTop
          let node = document.createElement("div")
          node.className = "bullet_item"
          $(".enemy_bullet").appendChild(node)
          timeEnemyBullet = setInterval(() => {
            left -= enemySpeed
            node.style.left = left + 'px'
            node.style.top = top + 30 + 'px'
            if (left <= 0) node.remove()
          }, 1)
        })
      }
    }

    // 陨石
    s++
    if (s > 600) {
      s = 0
      let meteoriteNode = document.createElement("div")
      meteoriteNode.className = 'meteorite_item'
      meteoriteNode.setAttribute('index', 1)
      meteoriteNode.style.top = randomHeight + 'px'
      meteoriteNode.innerHTML = `<img src="./images/aestroid_brown.png" alt="">`
      $(".meteorite").appendChild(meteoriteNode)
    }
    // 陨石销毁
    $2(".meteorite_item").forEach(item => item.offsetLeft <= -50 ? item.remove() : '')

    // 小行星
    x++
    if (x > 500) {
      x = 0
      let randomNum = Math.floor(Math.random() * 5)
      let aestroidNode = document.createElement("div")
      aestroidNode.className = 'aestroid_item'
      if (randomNum == 0) {
        randomHeight >= 250 ? aestroidNode.style.top = randomHeight + 100 + 'px' : aestroidNode.style.top = randomHeight + 'px'
        aestroidNode.innerHTML = `<img src="./images/planets/001-global.png" alt="">`
        $(".aestroid_one").appendChild(aestroidNode)
      } else if (randomNum == 1) {
        randomHeight >= 300 ? aestroidNode.style.top = randomHeight + 100 + 'px' : aestroidNode.style.top = randomHeight + 'px'
        aestroidNode.innerHTML = `<img src="./images/planets/002-travel.png" alt="">`
        $(".aestroid_two").appendChild(aestroidNode)
      } else if (randomNum == 2) {
        randomHeight >= 400 ? aestroidNode.style.top = randomHeight + 200 + 'px' : aestroidNode.style.top = randomHeight + 'px'
        aestroidNode.innerHTML = `<img src="./images/planets/006-mars.png" alt="">`
        $(".aestroid_three").appendChild(aestroidNode)
      } else if (randomNum == 3) {
        randomHeight >= 512 ? aestroidNode.style.top = randomHeight + 200 + 'px' : aestroidNode.style.top = randomHeight + 'px'
        aestroidNode.innerHTML = `<img src="./images/planets/009-saturn.png" alt="">`
        $(".aestroid_four").appendChild(aestroidNode)
      } else {
        randomHeight >= 515 ? aestroidNode.style.top = randomHeight + 300 + 'px' : aestroidNode.style.top = randomHeight + 'px'
        aestroidNode.innerHTML = `<img src="./images/planets/005-science.png" alt="">`
        $(".aestroid_five").appendChild(aestroidNode)
      }
    }
    // 小行星销毁
    $2(".aestroid_cont .aestroid_item").forEach(item => item.offsetLeft <= -200 ? item.remove() : '')
    // 生成燃料
    r++
    if (r > 300) {
      r = 0
      let left = Math.floor(Math.random() * document.body.clientWidth)
      let node = document.createElement("div")
      node.className = "fuel_item"
      node.innerHTML = `<div class="fuel_top"></div><div class="fuel_center"></div>`
      node.style.left = left + 'px'
      $(".fuel_cont").appendChild(node)
      setInterval(() => {
        $2(".fuel_item").forEach(item => {
          let top = Number(getComputedStyle(item, null)['top'].substring(0, getComputedStyle(item, null)['top'].length - 2))
          if (top >= document.body.clientHeight + 50) item.remove()
        })
      }, 100)
    }
    // 执行碰撞
    collision()
  }, 1000 / 60)
}
// 敌机动画
function enemyAnmiation() {
  let index = 1
  timeEnemyanimation = setInterval(() => {
    index == 4 ? index = 1 : index++
    $2('.enemy_item img').forEach(item => item.src = `./images/敌机${index}.png`)
  }, 100)
}
// 友机动画
function friendlyAnmiation() {
  let index = 1
  timeFriendlyAnimation = setInterval(() => {
    index == 4 ? index = 1 : index++
    $2('.friendly_item img').forEach(item => item.src = `./images/友机${index}.png`)
  }, 100)
}
// 碰撞检测
function collision() {
  // 我方子弹
  $2(".laynch_item").forEach(item => {
    let laynchTop = item.offsetTop
    let laynchLeft = item.offsetLeft
    let laynchRight = item.offsetLeft + item.offsetWidth
    let laynchBottom = item.offsetTop + item.offsetHeight
    // 子弹&敌机
    $2(".enemy_item").forEach(item2 => {
      let Top = item2.offsetTop
      let Left = item2.offsetLeft
      let Right = item2.offsetLeft + item2.offsetWidth
      let Bottom = item2.offsetTop + item2.offsetHeight
      // 我方子弹和敌机的碰撞
      if (laynchLeft < Right && laynchRight > Left && laynchBottom > Top && laynchTop < Bottom) {
        music ? $("#destroyed").play() : $("#destroyed").pause() && $("#destroyed").load()
        item.remove()
        item2.remove()
        fraction += 5
        $(".score").innerHTML = `${fraction}分`
      }
    })
    // 子弹&友机
    $2(".friendly_item").forEach(item3 => {
      let Top = item3.offsetTop
      let Left = item3.offsetLeft
      let Right = item3.offsetLeft + item3.offsetWidth
      let Bottom = item3.offsetTop + item3.offsetHeight
      // 我方子弹和友机的碰撞
      if (laynchLeft < Right && laynchRight > Left && laynchBottom > Top && laynchTop < Bottom) {
        item.remove()
        item3.remove()
        fraction -= 10
        $(".score").innerHTML = `${fraction}分`
        music ? $("#destroyed").play() : $("#destroyed").pause() && $("#destroyed").load()
      }
    })
    // 子弹&陨石
    $2(".meteorite_item").forEach(item4 => {
      let Top = item4.offsetTop
      let Left = item4.offsetLeft
      let Right = item4.offsetLeft + item4.offsetWidth
      let Bottom = item4.offsetTop + item4.offsetHeight
      // 我方子弹和陨石的碰撞
      if (laynchLeft < Right && laynchRight > Left && laynchBottom > Top && laynchTop < Bottom) {
        let index = Number(item4.getAttribute('index'))
        item.remove()
        if (index >= 2) {
          music ? $("#destroyed").play() : $("#destroyed").pause() && $("#destroyed").load()
          item4.remove()
          fraction += 10
          $(".score").innerHTML = `${fraction}分`
        } else {
          index += 1
          item4.setAttribute('index', index)
        }
      }
    })
  })
  // 我方飞机的位置
  let aircraft = $(".aircraft_cont")
  let airTop = aircraft.offsetTop
  let airLeft = aircraft.offsetLeft
  let airRight = aircraft.offsetLeft + aircraft.offsetWidth
  let airBottom = aircraft.offsetTop + aircraft.offsetHeight
  // 我方飞机&敌机
  $2(".enemy_item").forEach(item => {
    let Top = item.offsetTop
    let Left = item.offsetLeft
    let Right = item.offsetLeft + item.offsetWidth
    let Bottom = item.offsetTop + item.offsetHeight
    if (airLeft < Right && airRight > Left && airBottom > Top && airTop < Bottom) {
      item.remove()
      let width = Number(getComputedStyle($(".progress"), null)['width'].substring(0, getComputedStyle($(".progress"), null)['width'].length - 2))
      width >= 50 ? width -= 50 : width = 0
      $(".fuelCounter span").innerHTML = Math.floor(width / 3.33) < 1 ? 0 : Math.floor(width / 3.33)
      $(".progress").style.width = width + 'px'
    }
  })
  // 我方飞机&友机
  $2(".friendly_item").forEach(item => {
    let Top = item.offsetTop
    let Left = item.offsetLeft
    let Right = item.offsetLeft + item.offsetWidth
    let Bottom = item.offsetTop + item.offsetHeight
    if (airLeft < Right && airRight > Left && airBottom > Top && airTop < Bottom) {
      item.remove()
      let width = Number(getComputedStyle($(".progress"), null)['width'].substring(0, getComputedStyle($(".progress"), null)['width'].length - 2))
      width >= 50 ? width -= 50 : width = 0
      $(".fuelCounter span").innerHTML = Math.floor(width / 3.33) < 1 ? 0 : Math.floor(width / 3.33)
      $(".progress").style.width = width + 'px'
    }
  })
  // 我方飞机&小行星
  $2(".meteorite_item").forEach(item => {
    let Top = item.offsetTop
    let Left = item.offsetLeft
    let Right = item.offsetLeft + item.offsetWidth
    let Bottom = item.offsetTop + item.offsetHeight
    if (airLeft < Right && airRight > Left && airBottom > Top && airTop < Bottom) {
      item.remove()
      let width = Number(getComputedStyle($(".progress"), null)['width'].substring(0, getComputedStyle($(".progress"), null)['width'].length - 2))
      width >= 50 ? width -= 50 : width = 0
      $(".fuelCounter span").innerHTML = Math.floor(width / 3.33) < 1 ? 0 : Math.floor(width / 3.33)
      $(".progress").style.width = width + 'px'
    }
  })
  // 我方飞机&敌方子弹
  $2(".bullet_item").forEach(item => {
    let Top = item.offsetTop
    let Left = item.offsetLeft
    let Right = item.offsetLeft + item.offsetWidth
    let Bottom = item.offsetTop + item.offsetHeight
    if (airLeft < Right && airRight > Left && airBottom > Top && airTop < Bottom) {
      item.remove()
      let width = Number(getComputedStyle($(".progress"), null)['width'].substring(0, getComputedStyle($(".progress"), null)['width'].length - 2))
      width >= 50 ? width -= 50 : width = 0
      $(".fuelCounter span").innerHTML = Math.floor(width / 3.33) < 1 ? 0 : Math.floor(width / 3.33)
      $(".progress").style.width = width + 'px'
    }
  })
  // 我方飞机&燃料
  $2(".fuel_item").forEach(item => {
    let Top = item.offsetTop
    let Left = item.offsetLeft
    let Right = item.offsetLeft + item.offsetWidth
    let Bottom = item.offsetTop + item.offsetHeight
    if (airLeft < Right && airRight > Left && airBottom > Top && airTop < Bottom) {
      item.remove()
      let width = Number(getComputedStyle($(".progress"), null)['width'].substring(0, getComputedStyle($(".progress"), null)['width'].length - 2))
      if (width > 50) {
        width = 100
        $(".fuelCounter span").innerHTML = 30
      } else {
        width += 50
      }
      $(".progress").style.width = width + 'px'
    }
  })
}
// 音乐的暂停与播放
function pause_music() {
  if (music) {
    $("#background").play()
    $(".pause_music img").src = "./images/音乐.png"
  } else {
    $("#background").pause()
    $(".pause_music img").src = "./images/静音.png"
  }
}
// 游戏暂停
function pause_games() {
  pause_game = !pause_game
  if (pause_game) {
    $(".pause_game img").src = "./images/暂停.png"
    music = false
    pause_music()
    $(".background").style.animationPlayState = "paused"
    $2(".enemy_item").forEach(item => item.style.animationPlayState = "paused")
    $2(".friendly_item").forEach(item => item.style.animationPlayState = "paused")
    $2(".aestroid_item").forEach(item => item.style.animationPlayState = "paused")
    $2(".meteorite_item").forEach(item => item.style.animationPlayState = "paused")
    $2(".meteorite_item img").forEach(item => item.style.animationPlayState = "paused")
    $2(".fuel_item").forEach(item => item.style.animationPlayState = "paused")
    $2(".flame").forEach(item => item.style.animationPlayState = "paused")
    clearInterval(timedate)
    clearInterval(timeCreateAir)
    clearInterval(timeEnemyanimation)
    clearInterval(timeFriendlyAnimation)
    clearInterval(timerkey)
    clearInterval(timelatnch)
    clearInterval(timeEnemyBullet)
    clearInterval(timerController)
  } else {
    $(".pause_game img").src = "./images/继续.png"
    music = true
    pause_music()
    startTime()
    $(".background").style.animationPlayState = "running"
    $2(".enemy_item").forEach(item => item.style.animationPlayState = "running")
    $2(".friendly_item").forEach(item => item.style.animationPlayState = "running")
    $2(".aestroid_item").forEach(item => item.style.animationPlayState = "running")
    $2(".meteorite_item").forEach(item => item.style.animationPlayState = "running")
    $2(".meteorite_item img").forEach(item => item.style.animationPlayState = "running")
    $2(".fuel_item").forEach(item => item.style.animationPlayState = "running")
    $2(".flame").forEach(item => item.style.animationPlayState = "running")
    createAircraft()
    enemyAnmiation()
    friendlyAnmiation()
    keyboard()
    laynchContinue()
    enemyContinue()
    controller()
  }
}
// 子弹继续射击 
function laynchContinue() {
  clearInterval(timeContinue)
  $2(".laynch_item").forEach(item => {
    let left = item.offsetLeft
    let top = item.offsetTop
    timeContinue = setInterval(() => {
      left += laynchSpeed
      item.style.left = left + 'px'
      item.style.top = top + 'px'
      if (left >= document.body.clientWidth) item.remove()
    }, 1)
  })
}
// 敌方子弹继续射击 
function enemyContinue() {
  clearInterval(timeContinue2)
  $2(".bullet_item").forEach(item => {
    let left = item.offsetLeft
    let top = item.offsetTop
    timeContinue2 = setInterval(() => {
      left -= enemySpeed
      item.style.left = left + 'px'
      item.style.top = top + 'px'
      if (left >= document.body.clientWidth) item.remove()
    }, 1)
  })
}
// 结束游戏
function endGame() {
  $('.submit').onclick = function () {
    console.log(1)
    let userName = $(".userName").value
    let arr2 = []
    if (userName.length !== 0) {
      obj.name = userName
      obj.time = timeIndex
      obj.score = fraction
      if (arr !== []) {
        arr.push(obj)
        save(arr, 'value')
      } else {
        arr2.push(obj)
        save(arr2, 'value')
      }
      $('.infoTable').style.transform = `translate(-50%,-50%) scale(0)`
      $('.ranking').style.transform = `translate(-50%,-50%) scale(1)`
      ranking()
    } else {
      $(".userName").style.borderColor = "red"
    }
  }
}
// 排行榜
function ranking() {
  if (arr !== []) {
    $('.tbody').innerHTML = ''
    arr.sort((a, b) => {
      return b.score - a.score ? b.score - a.score : a.time - b.time && a.score == b.score ? b.time - a.time : a.time - b.time
    });
    let pos = 1;
    arr.forEach((item, index) => {
      let res = 1;
      if (arr[index].score == arr[index - 1]?.score && arr[index].time == arr[index - 1]?.time) {
        res = pos;
      } else {
        res = pos = index + 1;
      }
      $('.tbody').innerHTML += `
      <tr>
        <td>${res}</td>
        <td>${item.name}</td>
        <td>${item.score}分</td>
        <td>${item.time}秒</td>
      </tr>
      `
    })
  }
}